import { useState, useEffect } from "react";
import { cardApi } from "../lib/cardApi";
import TrendCardMobile from "./TrendCardMobile";
import ProductCardMobile from "./ProductCardMobile";
import { isValidCardContent } from "../utils/cardUtils";
import { transformApiDataToTrendCard } from '../services/trendCardService';
import { transformApiDataToProductCard } from '../services/productCardService';

interface UniversalCardProps {
  cardContent: string;
}

interface ApiResponse {
  type: 'line' | 'product' | 'bar' | 'pie';
  data: any;
}

export default function UniversalCard({ cardContent }: UniversalCardProps) {
  const [apiData, setApiData] = useState<ApiResponse | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // 获取卡片数据
  useEffect(() => {
    if (!isValidCardContent(cardContent)) {
      setApiData(null);
      setLoading(false);
      setError(null);
      return;
    }
    
    setLoading(true);
    setError(null);
    
    // 使用AbortController来取消请求
    const abortController = new AbortController();
    let isMounted = true;
    
    // 统一使用cardApi，由API返回决定卡片类型
    cardApi.getCardByCardContent(cardContent)
      .then((response: any) => {
        // 检查组件是否仍然挂载且请求未被取消
        if (!isMounted || abortController.signal.aborted) return;
        
        if (!response.success) {
          setError(response.error || '获取数据失败');
          setLoading(false);
          return;
        }
        // 完全使用API返回的type
        setApiData({ type: response.data.type, data: response.data });
        setLoading(false);
      })
      .catch((err: any) => {
        // 只在组件仍然挂载且请求未被取消时处理错误
        if (!isMounted || abortController.signal.aborted) return;
        
        // 忽略取消请求的错误
        if (err.name === 'AbortError') return;
        
        console.error('获取卡片数据失败:', err);
        setError('获取数据失败');
        setLoading(false);
      });
    
    // 清理函数：组件卸载时取消请求
    return () => {
      isMounted = false;
      abortController.abort();
    };
  }, [cardContent]); // 只依赖cardContent

  if (loading) {
    return (
      <div style={{ 
        display: "flex", 
        justifyContent: "center", 
        alignItems: "center", 
        padding: "8px",
        margin: "4px 0" 
      }}>
        <div style={{
          width: "16px",
          height: "16px",
          border: "2px solid #e0e0e0",
          borderTop: "2px solid #1890ff",
          borderRadius: "50%",
          animation: "spin 1s linear infinite"
        }}></div>
        <style>{`
          @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
          }
        `}</style>
      </div>
    );
  }

  // 当没有有效数据时，直接返回null隐藏卡片
  if (error || !apiData) {
    return null;
  }

  // 根据API返回的type决定渲染什么组件
  switch (apiData.type) {
    case 'line':
      return <TrendCardMobile cardContent={cardContent} data={transformApiDataToTrendCard(apiData.data, cardContent)} />;
    case 'product':
      return <ProductCardMobile data={transformApiDataToProductCard(apiData.data, cardContent)} />;
    default:
      return null;
  }
} 